package com.xhs.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import com.xhs.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @desc:
 * @projectName: tools-parent
 * @author: xhs
 * @date: 2023/3/13 21:02
 * @version: JDK 1.8
 */
@Slf4j
@Service
public class UploadFileServiceImpl implements UploadFileService {

    @Value("${upload.filePath}")
    private String path;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public ReturnResult<Object> uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        log.info("文件名称filename:{}", filename);
        String name = StrUtil.subAfter(filename, ".", false);
        // 随机id
        String uuid = IdUtil.simpleUUID();
        filename = uuid + "." + name;
        log.info("新文件名称filename:{}", filename);
        // 上传文件的路径
        String realPath = path;
        Date date = DateUtil.date();
        realPath = realPath + DateUtil.year(date) + StrUtil.SLASH + (DateUtil.month(date) + 1) + StrUtil.SLASH;
        log.info("文件保存地址realPath:{}", realPath);
        // 保存文件的文件夹
        File dir = new File(realPath);
        if (!dir.exists()) {
            //若是文件路径不存在，就新建文件路径
            dir.mkdirs();
        }
        File uploadFile = new File(dir, filename);
        try {
            // 上传文件
            file.transferTo(uploadFile);
        } catch (IOException e) {
            log.info(":{}", e.getMessage());
            return ReturnResult.build(Result.UPLOAD_FILE_ERROR);
        }
        // 文件路径
        String filePath = realPath + filename;
        log.info("文件路径filePath：{}", filePath);
        return ReturnResult.build(Result.UPLOAD_FILE_SUCCESS).setData(filePath);
    }
}
